package com.pine.app.module.security.core.authorize.manager.impl;

import com.pine.app.module.security.core.authorize.annotation.ResourceAuthorize;
import com.pine.app.module.security.core.authorize.manager.ResourceAuthorizeManager;
import com.pine.app.module.security.core.common.enums.ErrorType;
import com.pine.app.module.security.core.exception.AccessDeniedException;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author xiaoyuan
 * @create 2020/3/13 14:48
 **/

public class DefaultResourceAuthorizeManagerImpl implements ResourceAuthorizeManager {
    @Override
    public void authorize(Set<String> resource, Class<?> target, Method method) {
        if(CollectionUtils.isEmpty(resource)){
            ErrorType.UNAUTHORIZED_CLIENT.throwThis(AccessDeniedException::new);
        }
        ResourceAuthorize classRA =
                AnnotationUtils.findAnnotation(target, ResourceAuthorize.class);
        ResourceAuthorize methodRA =
                AnnotationUtils.findAnnotation(method, ResourceAuthorize.class);
        if(classRA!=null){
            if(!resource.contains(classRA.value())){
                ErrorType.UNAUTHORIZED_CLIENT.throwThis(AccessDeniedException::new);
            }
        }else{
            if(methodRA!=null&&!resource.contains(methodRA.value())){
                ErrorType.UNAUTHORIZED_CLIENT.throwThis(AccessDeniedException::new);
            }
        }

    }
}
